package nl.justobjects.pushlet.client;

import java.io.Serializable;
import java.util.Map;

import nl.justobjects.pushlet.util.PushletException;

import org.springframework.beans.factory.InitializingBean;

public class PushletClientService implements InitializingBean {

	private PushletClientListenerContainer pushletClientListenerContainer;
	private PushletClientConnectionFactory pushletClientConnectionFactory;
	
	private boolean asyn = false;
	private int threadSize = 10;
	
	public boolean isAsyn() {
		return asyn;
	}

	public void setAsyn(boolean asyn) {
		this.asyn = asyn;
	}

	public int getThreadSize() {
		return threadSize;
	}

	public void setThreadSize(int threadSize) {
		this.threadSize = threadSize;
	}

	public void setPushletClientConnectionFactory(PushletClientConnectionFactory pushletClientConnectionFactory) {
		this.pushletClientConnectionFactory = pushletClientConnectionFactory;
	}
	public void setPushletClientListenerContainer(PushletClientListenerContainer pushletClientListenerContainer) {
		this.pushletClientListenerContainer = pushletClientListenerContainer;
	}
	
	public PushletClientService() {
		
	}

	public void subscribe(String subject, String label, PushletClientCallBack callBack) {
		try {
			this.pushletClientConnectionFactory.getConnection().subscribe(subject, label);
		} catch (PushletException e) {
			e.printStackTrace();
		}
		pushletClientListenerContainer.register(subject, callBack);
	}
	
	public void unsubscribe(String subject, String label){
		try {
			this.pushletClientConnectionFactory.getConnection().unsubscribe(subject, label);
		} catch (PushletException e) {
			e.printStackTrace();
		}
		pushletClientListenerContainer.unregister(subject);
	}
	
	/**
	 * destroy-method
	 * @throws PushletException
	 */
	public void leave() {
		try {
			this.pushletClientConnectionFactory.getConnection().leave();
		} catch (PushletException e) {
			e.printStackTrace();
		}
		pushletClientListenerContainer.stop();
	}
	
	// TODO 现在支持简单的数据
	public void mutilcastEvent(String subject, String label, Map<String, Serializable> data) {
        try {
        	this.pushletClientConnectionFactory.getConnection().publish(subject, label, data);
        } catch (PushletException e) {
            e.printStackTrace();
        }
    }
	public void unicatEvent(String pid, String subject, String label, Map<String, Serializable> data) {
		
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.pushletClientListenerContainer = new PushletClientListenerContainer(this.threadSize, this.asyn);
		this.pushletClientConnectionFactory.setPushletClientListenerContainer(this.pushletClientListenerContainer);
		// 加载时完成pushlet服务器端注册session
        this.pushletClientConnectionFactory.connect();
	}
}
